package com.in.utils;

import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.net.URL;

/**
 * @ClassName IpUtil
 * @Description ip工具类
 * @Author liulianjia
 * @Date 2023/8/11 16:55
 */
@Slf4j
@Component
public class IpUtil {

    /**
     * 根据ip获取归属地
     *
     * @param ip
     * @return
     */
    public static String getAddress(String ip) throws IOException {
        URL url = HttpUtil.class.getClassLoader().getResource("ip2region.xdb");
        File file;
        if (url != null) {
            file = new File(url.getFile());
        } else {
            return null;
        }
        if (!file.exists()) {
            log.error("错误: 检测到无 ip2region.xdb 文件, 文件检测路径：" + file.getPath());
            return null;
        }
        // 1、创建 searcher 对象
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithFileOnly(file.getPath());
        } catch (IOException e) {
            log.error("创建对象失败,错误信息为: %s\n", e);
            return null;
        }

        String address = null;
        // 2、调用方法查询
        try {
            String region = searcher.search(ip);
            // 国家[0]|区域[1]|省份[2]|城市[3]|ISP(网络运营商)[4]
            String[] split = StringUtils.split(region, "|");
            address = split[0] + "." + split[2] + "." + split[3];
        } catch (Exception e) {
            log.error("调用程序出错,错误信息为: %s\n", e);
        } finally {
            // 3、关闭资源
            searcher.close();
        }

        return address;
    }

}
